# main.py
"""
医学AI助手主程序 - 增强版
集成扩展记忆类型、优化检索和深度反思的完整应用
"""
import sys
import os
import json
from datetime import datetime

# 添加当前目录到路径，以便导入模块
sys.path.append(os.path.dirname(__file__))

try:
    from memory_system.memory_manager import MemoryManager
    from reflection_engine.reflection import ReflectionEngine
except ImportError as e:
    print(f"❌ 导入模块失败: {e}")
    print("请确保所有必要的文件夹和文件都已创建")
    sys.exit(1)

def main():
    """主函数"""
    print("🎓 智能医学工程虚拟助手 - 增强版记忆与反思系统")
    print("=" * 60)
    print("✨ 新功能: 错题集管理 | 学习进度跟踪 | 知识缺口分析 | 优化检索算法")
    print("=" * 60)
    
    try:
        # 初始化系统
        print("🚀 初始化系统组件...")
        memory_manager = MemoryManager()
        reflection_engine = ReflectionEngine(memory_manager)
        
        print("✅ 系统初始化完成")
        print("\n📚 可用功能:")
        print("1. 基础记忆管理 - 存储和检索学习记录")
        print("2. 错题集管理 - 记录和分析学习错误")
        print("3. 学习进度跟踪 - 可视化学习轨迹")
        print("4. 知识缺口分析 - 智能识别薄弱环节")
        print("5. 优化检索算法 - 基于向量相似度的精准搜索")
        print("6. 深度反思引擎 - 综合数据分析生成洞察")
        
        # 演示增强功能
        print("\n🧪 运行增强功能演示...")
        demo_enhanced_functionality(memory_manager, reflection_engine)
        
        print("\n🎉 增强版系统准备就绪！")
        print("运行 'python tests/test_enhanced_features.py' 测试新功能")
        print("运行 'python tests/test_memory.py' 运行基础测试")
        
    except Exception as e:
        print(f"❌ 系统启动失败: {e}")
        import traceback
        traceback.print_exc()

def demo_enhanced_functionality(memory_manager, reflection_engine):
    """演示增强功能"""
    try:
        # 演示用户ID
        demo_user = "enhanced_demo_student"
        
        print(f"\n📝 为用户 {demo_user} 创建综合学习档案...")
        
        # 1. 演示错题记录功能
        print("\n🔴 1. 错题集管理演示")
        demo_mistakes = [
            {
                "question": "在医学影像分析中，哪种深度学习模型最适合处理3D CT数据？",
                "wrong_answer": "传统的2D CNN",
                "correct_answer": "3D CNN或V-Net",
                "knowledge_points": ["3D CNN", "医学影像", "CT数据", "深度学习"],
                "difficulty": "hard",
                "analysis": "未能理解3D数据需要3D卷积核来处理空间信息"
            },
            {
                "question": "医学图像预处理中，归一化的主要目的是什么？",
                "wrong_answer": "增加图像对比度",
                "correct_answer": "使不同来源的图像数据具有一致的数值范围",
                "knowledge_points": ["图像预处理", "归一化", "数据标准化"],
                "difficulty": "medium",
                "analysis": "混淆了归一化和对比度增强的概念"
            },
            {
                "question": "在训练深度学习模型时，过拟合的表现是什么？",
                "wrong_answer": "训练集和测试集准确率都很低",
                "correct_answer": "训练集准确率高但测试集准确率低",
                "knowledge_points": ["过拟合", "模型评估", "泛化能力"],
                "difficulty": "medium",
                "analysis": "对过拟合和欠拟合的概念理解不清"
            }
        ]
        
        for i, mistake_data in enumerate(demo_mistakes, 1):
            result = memory_manager.write_mistake(
                user_id=demo_user,
                question=mistake_data["question"],
                wrong_answer=mistake_data["wrong_answer"],
                correct_answer=mistake_data["correct_answer"],
                knowledge_points=mistake_data["knowledge_points"],
                difficulty=mistake_data["difficulty"],
                analysis=mistake_data["analysis"]
            )
            print(f"   ✅ 记录错题 {i}: {mistake_data['question'][:30]}...")
        
        # 2. 演示学习进度跟踪
        print("\n🟢 2. 学习进度跟踪演示")
        demo_progress = [
            {
                "course": "医学人工智能基础",
                "chapter": "深度学习原理",
                "progress": 0.9,
                "confidence": 0.8,
                "notes": "掌握了基本原理，需要更多实践"
            },
            {
                "course": "医学人工智能基础", 
                "chapter": "卷积神经网络",
                "progress": 0.7,
                "confidence": 0.6,
                "notes": "理解了CNN结构，但在医学应用上还需练习"
            },
            {
                "course": "医学影像处理",
                "chapter": "图像预处理技术",
                "progress": 0.6,
                "confidence": 0.5,
                "notes": "掌握了基础方法，需要学习高级技术"
            },
            {
                "course": "医学影像处理",
                "chapter": "分割算法",
                "progress": 0.4,
                "confidence": 0.3,
                "notes": "概念理解，实现有困难"
            }
        ]
        
        for progress_data in demo_progress:
            result = memory_manager.write_progress(
                user_id=demo_user,
                course=progress_data["course"],
                chapter=progress_data["chapter"],
                progress=progress_data["progress"],
                confidence=progress_data["confidence"],
                notes=progress_data["notes"]
            )
            print(f"   ✅ 记录进度: {progress_data['course']} - {progress_data['chapter']}")
        
        # 3. 演示基础交互记录
        print("\n🔵 3. 学习交互记录")
        demo_interactions = [
            "询问如何选择合适的激活函数用于医学图像分类",
            "讨论过拟合问题的解决方法在医学数据中的应用", 
            "请教迁移学习在医学影像分析中的最佳实践",
            "询问如何评估深度学习模型在医学任务中的性能"
        ]
        
        for interaction in demo_interactions:
            result = memory_manager.write_memory(
                user_id=demo_user,
                content=interaction,
                memory_type="interaction",
                metadata={
                    "course": "医学人工智能基础",
                    "tags": ["深度学习", "医学应用"],
                    "context": "理论学习"
                }
            )
            print(f"   ✅ 记录交互: {interaction[:25]}...")
        
        # 4. 演示检索功能
        print("\n🟣 4. 优化检索算法演示")
        
        # 4.1 检索特定类型的记忆
        print("   - 检索错题记录:")
        mistakes = memory_manager.get_user_mistakes(demo_user)
        for i, mistake in enumerate(mistakes[:3], 1):
            metadata = mistake.get("metadata", {})
            print(f"     {i}. {mistake['content'][:50]}...")
            print(f"       知识点: {metadata.get('knowledge_points', '未知')}")
        
        # 4.2 向量相似度搜索
        print("\n   - 向量相似度搜索 '医学图像预处理':")
        similar_memories = memory_manager.search_similar_memories(
            query_text="医学图像预处理",
            user_id=demo_user,
            similarity_threshold=0.5
        )
        for i, memory in enumerate(similar_memories[:2], 1):
            print(f"     {i}. [{memory['type']}] {memory['content'][:40]}...")
            print(f"        相似度: {memory['similarity_score']}")
        
        # 5. 演示学习进度分析
        print("\n🟠 5. 学习进度分析")
        progress_data = memory_manager.get_learning_progress(demo_user)
        print(f"   - 整体学习进度: {progress_data['overall_progress'] * 100:.1f}%")
        
        for course, data in progress_data.get("course_progress", {}).items():
            print(f"   - {course}:")
            print(f"     平均进度: {data['average_progress'] * 100:.1f}%")
            print(f"     平均掌握度: {data['average_confidence'] * 100:.1f}%")
            chapters = data.get("chapters", [])
            if chapters:
                latest = max(chapters, key=lambda x: x.get('timestamp', ''))
                print(f"     最近学习: {latest.get('chapter', '未知')}")
        
        # 6. 演示知识缺口分析
        print("\n🔴 6. 知识缺口分析")
        gap_analysis = memory_manager.get_knowledge_gap_analysis(demo_user)
        
        if gap_analysis.get("weak_knowledge_points"):
            print("   - 薄弱知识点排名:")
            for i, weak_point in enumerate(gap_analysis["weak_knowledge_points"][:3], 1):
                print(f"     {i}. {weak_point['point']} (错误次数: {weak_point['mistake_count']})")
        
        if gap_analysis.get("recommendations"):
            print("   - 个性化学习建议:")
            for i, recommendation in enumerate(gap_analysis["recommendations"], 1):
                print(f"     {i}. {recommendation}")
        
        # 7. 演示深度反思引擎
        print("\n🟢 7. 深度反思引擎演示")
        print("   正在分析学习数据并生成深度洞察...")
        
        reflection_result = reflection_engine.trigger_comprehensive_reflection(demo_user, "deep_analysis")
        
        if reflection_result["status"] == "success":
            analysis = reflection_result.get("learning_analysis", {})
            ai_insights = reflection_result.get("ai_insights", {})
            
            print("   - 学习状态评估:")
            print(f"     学习动力: {analysis.get('learning_momentum', '未知')}")
            print(f"     知识稳定性: {analysis.get('knowledge_stability', '未知')}")
            
            if analysis.get("improvement_areas"):
                print(f"     需改进领域: {', '.join(analysis['improvement_areas'])}")
            
            if analysis.get("strengths"):
                print(f"     优势领域: {', '.join(analysis['strengths'])}")
            
            print("\n   - AI教学洞察:")
            if ai_insights.get("teaching_insights"):
                for i, insight in enumerate(ai_insights["teaching_insights"][:3], 1):
                    print(f"     {i}. {insight}")
            
            if ai_insights.get("urgent_improvements"):
                print("\n   - 急需改进的领域:")
                for i, area in enumerate(ai_insights["urgent_improvements"], 1):
                    print(f"     {i}. {area}")
        
        # 8. 演示记忆统计
        print("\n📊 8. 记忆系统统计")
        memory_types = ["interaction", "mistake", "progress", "derived_knowledge"]
        
        for mem_type in memory_types:
            memories = memory_manager.read_memory(demo_user, memory_type=mem_type, limit=100)
            if memories:
                type_name = memory_manager.MEMORY_TYPES.get(mem_type, mem_type)
                print(f"   - {type_name}: {len(memories)} 条记录")
        
        print("\n✨ 增强功能演示完成！")
        print("\n💡 系统亮点总结:")
        print("   • 多类型记忆管理：错题、进度、交互、衍生知识")
        print("   • 智能检索：基于向量相似度的精准搜索")
        print("   • 深度分析：知识缺口识别和学习状态评估") 
        print("   • 个性化建议：基于数据分析的定制化学习路径")
        print("   • 持续改进：反思引擎自动优化教学策略")
        
    except Exception as e:
        print(f"❌ 演示失败: {e}")
        import traceback
        traceback.print_exc()

def quick_test():
    """快速测试函数 - 用于验证核心功能"""
    print("\n⚡ 快速功能验证...")
    
    try:
        mm = MemoryManager()
        
        # 快速写入测试数据
        test_result = mm.write_memory(
            user_id="quick_test_user",
            content="快速测试：医学AI系统功能验证",
            memory_type="interaction",
            metadata={"test": True}
        )
        
        if test_result["status"] == "success":
            print("✅ 核心功能正常")
        else:
            print("❌ 核心功能异常")
            
    except Exception as e:
        print(f"❌ 快速测试失败: {e}")

if __name__ == "__main__":
    # 检查命令行参数
    if len(sys.argv) > 1 and sys.argv[1] == "quick":
        quick_test()
    else:
        main()